package com.bjtu.ptsite.utils;

import com.bjtu.ptsite.model.AnnounceRequest;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static net.i2p.crypto.eddsa.Utils.bytesToHex;

public class AnnounceParamParser {

    public static AnnounceRequest parse(String passKey, Map<String, String> params, String clientIp,String queryString) throws UnsupportedEncodingException {
        AnnounceRequest request = new AnnounceRequest();

        byte[] infoHash = InfoHashUtil.matchInfoHash(queryString);
        request.setPassKey(passKey);

        //String infoHashParam = params.get("info_hash");
        ////            byte[] infoHashBytes = infoHashParam.getBytes(StandardCharsets.ISO_8859_1);
        // 解析 info_hash（20字节，URL 编码）
        String infoHashEncoded = params.get("info_hash");
//        byte[] bytes = parseInfoHash(infoHashEncoded);
        //byte[] infoHashBytes = infoHashEncoded.getBytes(StandardCharsets.ISO_8859_1);
        //byte[] infoHashBytes = URLDecoder.decode(infoHashEncoded, "ISO-8859-1").getBytes("ISO-8859-1");
        request.setInfoHashBytes(infoHash);
        request.setInfoHashHex(bytesToHex(infoHash));

        // 解析 peer_id
        String peerId = params.get("peer_id");
        if (peerId != null) {
            request.setPeerId(URLDecoder.decode(peerId, "ISO-8859-1").getBytes());
        }

        // 解析其他字段
        request.setPort(parseInt(params.get("port"), 0));
        request.setUploaded(parseLong(params.get("uploaded"), 0L));
        request.setDownloaded(parseLong(params.get("downloaded"), 0L));
        request.setLeft(parseLong(params.get("left"), 0L));
        request.setEvent(params.getOrDefault("event", "none"));

        // 获取 IP（客户端未传则用实际请求来源）
        request.setIp(params.getOrDefault("ip", clientIp));

        if (params.containsKey("numwant")) {
            request.setNumwant(parseInt(params.get("numwant"), 50));
        }

        return request;
    }

    public static byte[] parseInfoHash(String encoded) throws UnsupportedEncodingException {
        byte[] result = new byte[20];
        int resultIndex = 0;
        for (int i = 0; i < encoded.length(); ) {
            char c = encoded.charAt(i);
            if (c == '%') {
                String hex = encoded.substring(i + 1, i + 3);
                result[resultIndex++] = (byte) Integer.parseInt(hex, 16);
                i += 3;
            } else {
                result[resultIndex++] = (byte) c;
                i++;
            }
        }
        return result;
    }

    private static int parseInt(String value, int defaultValue) {
        try {
            return value != null ? Integer.parseInt(value) : defaultValue;
        } catch (Exception e) {
            return defaultValue;
        }
    }

    private static long parseLong(String value, long defaultValue) {
        try {
            return value != null ? Long.parseLong(value) : defaultValue;
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b & 0xff));
        }
        return sb.toString();
    }


}

